package com.xnyzc.lhy.mis.service.impl.cms.invoice;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.finance.entity.invoice.TcInvoiceInfo;
import com.xnyzc.lhy.mis.entity.result.cms.invoice.TcInvoiceInfoResults;
import com.xnyzc.lhy.mis.mapper.cms.invoice.TcInvoiceMapper;
import com.xnyzc.lhy.mis.service.cms.invoice.TcInvoiceService;
import nuonuo.open.sdk.NNOpenSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 同城发票接口实现类
 * @author zhaolijie
 * @date
 */

@Service
public class TcInvoiceServiceImpl implements TcInvoiceService {

    @Autowired
    private TcInvoiceMapper tcInvoiceMapper;

    @Override
    public Rv getInvoiceList(TcInvoiceInfoResults tcInvoiceInfoResults) {
        if (CheckUtil.objIsEmpty(tcInvoiceInfoResults.getCurrent(),tcInvoiceInfoResults.getSize())) {
            throw PangException.create(EErrorCode.missingArg);
        }

        IPage<TcInvoiceInfoResults> invoiceList = tcInvoiceMapper.getInvoiceList(new Page(tcInvoiceInfoResults.getCurrent(), tcInvoiceInfoResults.getSize()), tcInvoiceInfoResults);
        List<TcInvoiceInfoResults> records = invoiceList.getRecords();
        if (records.size()>0) {
            for (int i = 0; i < records.size(); i++) {
                String invoiceOrderIds = records.get(i).getOrderId();
                if (CheckUtil.strIsNotEmpty(invoiceOrderIds) && true == invoiceOrderIds.contains(",")){
                    String[] split = invoiceOrderIds.split(",");
                    //records.get(i).setChooseOrderId(split[0]);
                    List<String> orders = new ArrayList<>();
                    for (int j = 0; j < split.length; j++) {
                        orders.add(split[j]);
                    }
                    records.get(i).setOrderIds(orders);
                }
            }
        }
        invoiceList.setRecords(records);
        return  Rv.wrap(invoiceList);
    }
    @Override
    public Rv getInvoiceInfo(Long id) {
        if (CheckUtil.objIsEmpty(id)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        TcInvoiceInfo invoiceInfo = tcInvoiceMapper.selectById(id);
        if(invoiceInfo == null){
            throw PangException.create(EErrorCode.infoIsNull);
        }
        return Rv.wrap(invoiceInfo);
    }

    @Override
    public Rv getInvoiceListByCondition(TcInvoiceInfoResults tcInvoiceInfoResults) {
        if (CheckUtil.objIsEmpty(tcInvoiceInfoResults.getCurrent(),tcInvoiceInfoResults.getSize())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        IPage<TcInvoiceInfoResults> invoiceList = tcInvoiceMapper.getInvoiceListByCondition(new Page(tcInvoiceInfoResults.getCurrent(), tcInvoiceInfoResults.getSize()), tcInvoiceInfoResults);
        List<TcInvoiceInfoResults> records = invoiceList.getRecords();
        if (records.size()>0) {
            for (int i = 0; i < records.size(); i++) {
                String invoiceOrderIds = records.get(i).getOrderId();
                if (CheckUtil.strIsNotEmpty(invoiceOrderIds) && true == invoiceOrderIds.contains(",")){
                    String[] split = invoiceOrderIds.split(",");
                    //records.get(i).setChooseOrderId(split[0]);
                    List<String> orders = new ArrayList<>();
                    for (int j = 0; j < split.length; j++) {
                        orders.add(split[j]);
                    }
                    records.get(i).setOrderIds(orders);
                }
            }
        }
        invoiceList.setRecords(records);
        return  Rv.wrap(invoiceList);
    }

    /**
     * 更新发票状态和url地址
     * @param id
     * @return
     */
    @Override
    public Rv getInvoiceInfoById(Long id) {
        if (CheckUtil.objIsEmpty(id)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        //查看是否存在发票信息
        TcInvoiceInfo invoiceInfo = tcInvoiceMapper.selectById(id);
        if(invoiceInfo == null || CheckUtil.objIsEmpty(invoiceInfo.getInvoiceSerialNum())){
            throw PangException.create(EErrorCode.infoIsNull);
        }
        //获取诺诺令牌
        TcInvoiceInfo info2 = tcInvoiceMapper.selectById(1);
        if(info2 == null){
            info2.setId(1L);
            tcInvoiceMapper.insert(info2);
        }
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String taxnum = "91510107749745776R"; // 授权企业税号
        String appKey = "97771535";
        String appSecret = "4A3C10287D414583";
        String token = info2.getAccessToken();
        if(token == null){
            //自用型应用获取令牌
            String json = NNOpenSDK.getIntance().getMerchantToken(appKey,appSecret);
            System.out.println("json" + json);
            org.json.JSONObject jSONObject = new org.json.JSONObject(json);
            token = jSONObject.get("access_token").toString();

            info2.setAccessToken(token);
            tcInvoiceMapper.updateById(info2);
        }
        String method = "nuonuo.ElectronInvoice.queryInvoiceResult"; // API方法名
        String content = "{" +
                "\"isOfferInvoiceDetail\": \"1\"," +
                "\"orderNos\": []," +
                "\"serialNos\": [" +
                "\""+invoiceInfo.getInvoiceSerialNum()+"\"" +
                "] " +
                "}";
        String url = "https://sdk.nuonuo.com/open/v1/services"; // SDK请求地址
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
        String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
        System.out.println(result);
        try{
            org.json.JSONObject jSONObject2 = new org.json.JSONObject(result);
            String result2 = jSONObject2.get("result").toString();
            System.out.println("----->" + result2);
            org.json.JSONArray jSONOArray = new org.json.JSONArray(result2);
            System.out.println(jSONOArray);
            org.json.JSONObject jSONObject3 = (org.json.JSONObject) jSONOArray.get(0);

            String pdfUrl = jSONObject3.get("pdfUrl").toString();
            if(pdfUrl == null || pdfUrl == ""){
                return Rv.error(EErrorCode.addError);
            }
            //更新发票的信息
            invoiceInfo.setInvoiceUrl(pdfUrl);
            invoiceInfo.setInvoiceStatus(2);//已开票状态
            tcInvoiceMapper.updateById(invoiceInfo);
        }catch (Exception e){
            return Rv.error(EErrorCode.addError);
        }
        return Rv.wrap(invoiceInfo);
    }
}
